
package com.max.common.oauth.oauth10;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class OAuthParameter implements Serializable, Comparable
{
	private String name;
    
	private String value;
    
    private File file = null;
    
    private static final long serialVersionUID = -8708108746980739212L;

    public OAuthParameter(String name, String value) 
    {
        this.name = name;
        this.value = value;
    }

    public OAuthParameter(String name, File file) 
    {
        this.name = name;
        this.file = file;
    }
    
    
    public String getName()
    {
        return name;
    }
    
    public String getValue()
    {
        return value;
    }

    public File getFile() 
    {
        return file;
    }

    public boolean isFile()
    {
        return null != file;
    }
    
    

    public String toString() 
    {
        return "PostParameter{" +
                "name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", file=" + file +
                '}';
    }
    
    public int compareTo(Object o) 
    {
        int compared;
        
        OAuthParameter that = (OAuthParameter) o;
        compared = name.compareTo(that.name);
        
        if (0 == compared)
        	compared = value.compareTo(that.value);
        
        return compared;
    }
    
    
    public static String encodeParameters(OAuthParameter[] params) 
    {
        if (null == params) 
        {
            return "";
        }
        
        StringBuffer buf = new StringBuffer();
        
        for (int j = 0; j < params.length; j++) 
        {
            if (params[j].isFile()) 
            	throw new IllegalArgumentException("parameter [" + params[j].name + "]should be text");
            
            if (j != 0) 
            	buf.append("&");
            
            try 
            {
                buf.append(URLEncoder.encode(params[j].name, "UTF-8"))
                        .append("=").append(URLEncoder.encode(params[j].value, "UTF-8"));
            }
            catch (UnsupportedEncodingException e) 
            {
            	e.printStackTrace();
            }
        }
        
        return buf.toString();
    }
    
}
